package cn.com.higinet.dl.joa.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cn.com.higinet.dl.joa.service.SystemService;;

@Controller("systemController")
public class SystemController {
	
	@Autowired
	private SystemService systemService;
	
	public SystemService getSystemService(){
		return systemService;
	}
	
	public void setSystemService(SystemService systemService){
		this.systemService = systemService;
	}

	@RequestMapping(value="/", method=RequestMethod.GET)
	public String getMain(){
		
		return "main/index";
		
	}
	
	@RequestMapping(value="/main")
	public String getMainView(){
		return "main/index";
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value="/getSearch", method=RequestMethod.POST)
	public void getAllSearch(@RequestParam Map<String, Object> reqs, 
			HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
		//String userName = session.getAttribute("userName").toString();
		String text = request.getAttribute("text").toString();
		
		Map pageInfo = new HashMap();  
        pageInfo.put("page", 1);  
        pageInfo.put("total", 5); 
		String jsonStr = getJsonString(systemService.getAllSearch(reqs, request), pageInfo);
		response.setContentType("html/txt");  
        response.setCharacterEncoding("utf-8");  
        response.setHeader("Pragma", "no-cache");  
        response.setHeader("Cache-Control", "no-cache, must-revalidate");  
        response.setHeader("Pragma", "no-cache");  
        response.getWriter().write(jsonStr); 
        response.getWriter().flush(); 
        response.getWriter().close();
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })  
    private String getJsonString(List list, Map pageInfo) {  
		  List mapList = new ArrayList();  
	        for(int i = 0; i < list.size(); i++) {  
	        	Map<String, Object> map = (Map<String, Object>) list.get(i);
	        	
	            Map cellMap = new HashMap();  
	            cellMap.put("id", map.get("userId"));  
	            cellMap.put("cell", new Object[] {map.get("userName"), map.get("userPwd"), 
	            		map.get("realName") });     
	            mapList.add(cellMap);  
	        }  
	        pageInfo.put("rows", mapList);  
	        JSONObject object = new JSONObject();
	        object.putAll(pageInfo);
	        return object.toString();  
	}

	
}